import { onMounted, ref } from "vue";
import {
  addRtcmGroupApi,
  deleteRtcmGroupApi,
  getRtcmGroupApi,
  type RtcmGroupDTO,
  type RtcmGroupList,
  type RtcmGroupParams,
  updateRtcmGroupApi
} from "@/api/rtcmGroup";
import { ElMessage } from "element-plus";

export default function useRtcmGroupHooks() {
  const rtcmGroupForm = ref<RtcmGroupParams>({
    pageSize: 10,
    pageNum: 1,
    name: undefined
  });

  const loading = ref(false);

  /** rtcm分组列表 */
  const rtcmGroupList = ref<RtcmGroupList>([]);

  /** 获取分组 */
  const getRtcmGroup = async () => {
    loading.value = true;
    const res = await getRtcmGroupApi(rtcmGroupForm.value).finally(
      () => (loading.value = false)
    );
    if (res.code == 200) {
      rtcmGroupList.value = res.data.list.map(item => {
        return { ...item, flag: false };
      });
    }
  };

  /** 重置 */
  const reset = async () => {
    rtcmGroupForm.value = {
      pageSize: 100000,
      pageNum: 1,
      name: undefined
    };
    await getRtcmGroup();
  };

  /** 删除 **/
  const deleteGroup = async (id: number) => {
    const res = await deleteRtcmGroupApi(id);
    if (res.code == 200) {
      ElMessage.success("删除成功");
      await getRtcmGroup();
      return;
    }
    ElMessage.warning("删除失败");
  };

  const columns: TableColumnList = [
    {
      type: "index",
      minWidth: 50,
      align: "center",
      label: "序号"
    },
    {
      prop: "groupName",
      label: "分组名称",
      align: "center",
      minWidth: 100,
      formatter: (row: any) => {
        if (row.flag) {
          return <el-input v-model={row.groupName}></el-input>;
        }
        return row.groupName;
      }
    },
    {
      label: "操作",
      align: "center",
      minWidth: 100,
      fixed: "right",
      slot: "operation"
    }
  ];

  /** 新增分组表单 **/
  const rtcmGroupParams = ref<RtcmGroupDTO>({
    id: undefined,
    groupName: undefined
  });

  /** 新增分组 **/
  const addRtcmGroup = async () => {
    const res = await addRtcmGroupApi(rtcmGroupParams.value).finally(() => {
      getRtcmGroup();
    });
    if (res.code == 200) {
      ElMessage.success("添加成功");
      return;
    }
    ElMessage.warning("添加失败");
  };

  /** 修改分组 **/
  const updateRtcmGroup = async (data: RtcmGroupDTO) => {
    if (!data.flag) {
      data.flag = true;
    } else {
      const res = await updateRtcmGroupApi(data);
      if (res.code == 200) {
        ElMessage.success("修改成功");
        await getRtcmGroup();
        return;
      }
      ElMessage.warning("修改失败");
    }
  };

  onMounted(async () => {
    await getRtcmGroup();
  });
  return {
    rtcmGroupForm,
    loading,
    rtcmGroupList,
    rtcmGroupParams,
    getRtcmGroup,
    reset,
    deleteGroup,
    columns,
    addRtcmGroup,
    updateRtcmGroup
  };
}
